<template>
  <div class="app-container">
    <h2 style="text-align: center;">发布新课程</h2>

    <el-steps :active="1"
              align-center
              process-status="wait"
              style="margin-bottom:40px">
      <el-step title="填写课程基本信息" />
      <el-step title="创建课程大纲" />
      <el-step title="提交审核" />
    </el-steps>

    <el-form label-width="120px">
      <el-form-item label="课程标题">
        <el-input v-model="courseInfo.title"
                  placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写" />
      </el-form-item>
      <!-- 一级分类 -->
      <el-form-item label="课程类别">
        <el-select v-model="courseInfo.subjectParentId"
                   placeholder="请选择"
                   @change="subjectLevelOneChanged">
          <el-option v-for="subject in subjectNestedList"
                     :key="subject.id"
                     :label="subject.title"
                     :value="subject.id" />
        </el-select>
        <!-- 二级分类 -->
        <el-select v-model="courseInfo.subjectId"
                   placeholder="请选择">
          <el-option v-for="subject in subSubjectList"
                     :key="subject.id"
                     :label="subject.title"
                     :value="subject.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="课程讲师">
        <el-select v-model="courseInfo.teacherId"
                   placeholder="请选择">
          <el-option v-for="teacher in teacherList"
                     :key="teacher.id"
                     :label="teacher.name"
                     :value="teacher.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="总课时">
        <el-input-number v-model="courseInfo.lessonNum"
                         :min="0"
                         controls-position="right"
                         placeholder="请填写课程的总课时数" />
      </el-form-item>
      <el-form-item label="课程简介">
        <wang-editor @editorData="editorData" />
      </el-form-item>
      <el-form-item label="课程价格">
        <el-input-number v-model="courseInfo.price"
                         :min="0"
                         controls-position="right"
                         placeholder="免费课程请设置为0元" /> 元
      </el-form-item>
      <el-form-item label="课程封面">
        <el-upload :show-file-list="false"
                   :on-success="handleAvatarSuccess"
                   :before-upload="beforeAvatarUpload"
                   :action="BASE_API+'/eduoss/fileoss'"
                   class="avatar-uploader">
          <img v-if="courseInfo.cover"
               :src="courseInfo.cover"
               class="avatar">
          <i v-else
             class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   :disabled="saveBtnDisabled"
                   @click="next">保存并下一步</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import course from '@/api/edu/course'
import subject from '@/api/edu/subject'
import teacher from '@/api/edu/teacher'

import WangEditor from '@/components/Edit/wangEditor.vue'

const defaultForm = {
  title: '',
  subjectId: '',
  teacherId: '',
  lessonNum: 0,
  description: '',
  cover: '',
  price: 0
}

export default {
  components: {
    WangEditor
  },
  data() {
    return {
      courseInfo: defaultForm,
      saveBtnDisabled: false,
      subjectNestedList: [],
      subSubjectList: [],
      teacherList: [],
      BASE_API: process.env.VUE_APP_BASE_API,
      courseId: ''
    }
  },
  created() {
    this.init()
    this.initSubjectList()
    this.initTeacherList()
  },
  methods: {
    // 初始化方法
    init() {
      if (this.$route.params && this.$route.params.id) {
        this.subjectLevelOneChanged()
        const id = this.$route.params.id
        this.courseId = id
        this.getInfo()
      } else {
        this.courseInfo = { ...defaultForm }
      }
    },
    getInfo() {
      course.getCourseInfo(this.courseId).then(response => {
        this.courseInfo = response.data.courseInfoVo
        //   subject.getNestedTreeList()
        //     .then(response => {
        //       // 2 获取所有一级分类
        //       this.subjectNestedList = response.data.list
        //       // 3 把所有的一级分类数组进行遍历，
        //       for (var i = 0; i < this.subjectNestedList.length; i++) {
        //         // 获取每个一级分类
        //         var oneSubject = this.subjectNestedList[i]
        //         // 比较当前courseInfo里面一级分类id和所有的一级分类id
        //         if (this.courseInfo.subjectParentId === oneSubject.id) {
        //           // 获取一级分类所有的二级分类
        //           this.subSubjectList = oneSubject.children
        //         }
        //       }
        //     })
      })
    },
    next() {
      this.saveBtnDisabled = true
      if (!this.courseInfo.id) {
        this.saveData()
      } else {
        this.changeData()
        // this.$router.push({ path: '/edu/course/chapter/' + this.courseInfo.id })
      }
    },
    saveData() {
      course.saveCourseInfo(this.courseInfo).then(response => {
        console.log(response)
        this.$message({
          type: 'success',
          message: '保存成功!'
        })
        return response// 将响应结果传递给then
      }).then(response => {
        this.$router.push({ path: '/edu/course/chapter/' + response.data.courseId })
      }).catch((response) => {
        this.$message({
          type: 'error',
          message: response.message
        })
      })
    },
    changeData() {
      // course.updateCourseInfo(this.courseInfo).then(response => {
      //   console.log(response)
      // })
    },
    initSubjectList() {
      subject.getNestedTreeList().then(response => {
        this.subjectNestedList = response.data.list
      })
    },
    subjectLevelOneChanged(value) {
      for (let i = 0; i < this.subjectNestedList.length; i++) {
        if (this.subjectNestedList[i].id === value) {
          this.subSubjectList = this.subjectNestedList[i].children
          this.courseInfo.subjectId = ''
        }
      }
    },
    initTeacherList() {
      teacher.getList().then(response => {
        this.teacherList = response.data.items
      })
    },

    // 上传封面涉及的方法
    handleAvatarSuccess(res, file) {
      // console.log(URL.createObjectURL(file.raw))// base64编码
      // this.courseInfo.cover = res.data.url
      console.log(file)
      this.courseInfo.cover = res.data.raw
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 获取编辑器内的文本内容
    editorData(data) {
      this.courseInfo.description = data
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
}
.avatar {
  width: 50px;
  height: 50px;
  display: block;
}
</style>
